package cn.wolfcode.shop.seckillserver.web.controller.frontend;

import cn.wolfcode.shop.seckillapi.domain.OrderInfo;
import cn.wolfcode.shop.seckillapi.service.ISeckillOrderService;
import cn.wolfcode.shop.seckillserver.web.alipay.AlipayProperties;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by wolfcode-lanxw
 */
@RestController
@RequestMapping("/alipay")
public class PayController {

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayProperties alipayProperties;

    @RequestMapping("/pay")
    public void pay(String orderNo, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8;");
        OrderInfo orderInfo = seckillOrderService.findByOrderNo(orderNo);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderInfo.getOrderNo();
        //付款金额，必填
        String total_amount =orderInfo.getSeckillPrice()+"";
        System.out.println(total_amount);
        //订单名称，必填
        String subject = "秒杀商品";
        //商品描述，可空
        String body = orderInfo.getGoodName();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
         String result = alipayClient.pageExecute(alipayRequest).getBody();
        PrintWriter out = response.getWriter();
        //输出
        out.println(result);
    }
    @RequestMapping("/return_url")
    public void returnUrl(@RequestParam Map<String,String> params,HttpServletResponse response) throws Exception {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType()); //调用SDK验证签名
        System.out.println("同步通知");
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(params.get("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            response.sendRedirect("http://localhost:9898/order_detail.html?orderNo="+out_trade_no);
        }else {
            response.sendRedirect("http://localhost/50x.html");
        }
    }
    @RequestMapping("/notify_url")
    public String notifyUrl(@RequestParam Map<String,String> params,HttpServletResponse response) throws Exception {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType()); //调用SDK验证签名
        System.out.println("异步通知");
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = params.get("out_trade_no");
            //支付宝交易号
            String trade_no = params.get("trade_no");
            //交易状态
            String trade_status = params.get("trade_status");

            if(trade_status.equals("TRADE_FINISHED")){

            }else if (trade_status.equals("TRADE_SUCCESS")){
                //先判断支付的状态
                OrderInfo orderInfo = seckillOrderService.findByOrderNo(out_trade_no);

                if(orderInfo.getStatus().equals(OrderInfo.STATUS_ACCOUNT_PAID)){
                    //订单已经支付了
                    return "success";
                }else if(orderInfo.getStatus().equals(OrderInfo.STATUS_ARREARAGE)){
                    //订单处于未支付状态
                    //把订单更改成已支付.
                    boolean success = seckillOrderService.updatePayState(orderInfo.getOrderNo(),OrderInfo.STATUS_ACCOUNT_PAID);
                    if(success){
                        return "success";
                    }else{
                        //插入一条记录,通知用户和客服,说明这个订单是在超时之后才支付的，进行退款的操作.
                        return "success";
                    }

                }else{
                    //订单在系统中超时被取消了.但是我们已经支付了。把订单修改人工处理.做退款的操作.
                }
            }
            return "success";

        }else {//验证失败
            return "fail";
        }
    }
}
